package v1

import (
	"gohub/app/http/requests"
	"gohub/app/models/category"
	"gohub/pkg/response"

	"github.com/gin-gonic/gin"
)

type CategoriesController struct {
	BaseAPIController
}

func (ctrl *CategoriesController) Index(c *gin.Context) {
	request := requests.PaginationRequest{}
	if ok := requests.Validate(c, &request, requests.Pagination); !ok {
		return
	}

	data, pager := category.Paginate(c, 10)
	response.JSON(c, gin.H{
		"data":  data,
		"pager": pager,
	})
}

func (ctrl *CategoriesController) Store(c *gin.Context) {
	request := requests.CategoryRequest{}
	if ok := requests.Validate(c, &request, requests.CategorySave); !ok {
		return
	}

	_category := category.Category{
		Name:        request.Name,
		Description: request.Description,
	}
	_category.Create()

	if _category.ID > 0 {
		response.Created(c, _category)
	} else {
		response.Abort500(c, "创建失败，请稍后尝试~")
	}
}

func (ctrl *CategoriesController) Update(c *gin.Context) {
	_category := category.Get(c.Param("id"))
	if _category.ID == 0 {
		response.Abort404(c)
		return
	}

	// 表单验证
	request := requests.CategoryRequest{}
	if ok := requests.Validate(c, &request, requests.CategorySave); !ok {
		return
	}

	// 保存
	_category.Name = request.Name
	_category.Description = request.Description
	if rowsAffected := _category.Save(); rowsAffected > 0 {
		response.Data(c, _category)
	} else {
		response.Abort500(c)
	}
}

func (ctrl *CategoriesController) Delete(c *gin.Context) {
	_category := category.Get(c.Param("id"))
	if _category.ID == 0 {
		response.Abort404(c)
		return
	}

	if rowsAffected := _category.Delete(); rowsAffected > 0 {
		response.Success(c)
		return
	}

	response.Abort500(c, "删除失败，请稍后尝试~")
}
